package testJdk.thread.pool;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName : learn_jdk.thread.pool.SinglePoolUtil
 * @Description : 类描述
 * Created by cyd on 2021-10-23 23:01:30
 */
public class SinglePoolUtil {
    /**
     * 使用枚举来保证当前线程池是一个单例的，并且在springboot初始化的时候，只加载一次
     */
    private enum Singleton {
        /**
         * 单例的枚举对象
         */
        INSTANCE;

        private final ExecutorService threadPool;

        Singleton() {
            threadPool = new ThreadPoolExecutor(20,
                    40, 1L, TimeUnit.MINUTES,
                    new LinkedBlockingQueue<>(1000),
                    new ThreadFactoryBuilder().setNameFormat("thread-bigScreen-runner-%d").build(),
                    new ThreadPoolExecutor.AbortPolicy()
            );
        }

        public ExecutorService getInstance() {
            return threadPool;
        }
    }

    /**
     * 向外提供线程池对象
     *
     * @return 线程池
     */
    public static ExecutorService getThreadPool() {
        return Singleton.INSTANCE.getInstance();
    }

    public static void destroyThreadPool(ExecutorService exec) {
        if (exec != null) {
            exec.shutdown();
        }
    }
}
